import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout'
  },
  {
    path: '/login',
    // 路由的懒加载：当访问到这个路由的时候才会去加载对应的文件，提高了首屏的加载速度
    component: () => import('@/views/login')
  },
  {
    path: '/layout',
    component: () => import('@/views/layout'),
    redirect: '/layout/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/layout/home')
      },
      {
        path: 'mine',
        component: () => import('@/views/layout/mine')
      }
    ]
  },
  {
    path: '/search',
    component: () => import('@/views/search')
  },
  {
    path: '/search/:keyword',
    component: () => import('@/views/searchresult')
  },
  {
    path: '/article',
    component: () => import('@/views/articledetail')
  },
  {
    path: '/user/edit',
    component: () => import('@/views/useredit')
  },
  {
    path: '/chat',
    component: () => import('@/views/chat')
  }
]
const router = new VueRouter({
  routes: routes
})

// 把不需要登录就可以访问的路由路径写在这个数组中
const whiteList = ['/login', '/layout/home', '/search']

// 路由的全局前置守卫
router.beforeEach((to, from, next) => {
  // 获取token
  const token = store.state.user.token
  // 判断有无token
  if (token) { // 登录了
    // 放行
    next()
  } else { // 未登录
    // 如果要去的路由路径在白名单数组中，直接放行；否则跳转至登录页登录，并携带回调地址
    if (whiteList.includes(to.path)) {
      // 直接放行
      next()
    } else {
      // 跳转至登录页
      // next(false)：停留在原地不动
      next(`/login?redirect=${to.path}`)
    }
  }
})

export default router
